'''
Created on 17.7.2011

@author: gilead
'''

from math import pi, sin, cos
from panda3d.core import Point3  #@UnresolvedImport

from direct.showbase import DirectObject

class CameraManager(DirectObject.DirectObject):
    '''
    classdocs
    '''


    def __init__(self, camera, focItem):
        '''
        Constructor
        '''
        self.focusShip = focItem
        self.camera = camera
        
        self.accept('own_ship_created', self.SetFocusShip)
        
        # maksimietaisyys katsomiselle
        self.viewMaxDistance = 270
        
        # kuinka suuri osuus ruudusta pitaa raahata, jotta kuvakulmaa vaihdetaan kokonaan?
        # (0,1)
        self.mouseSensitivity = 1
        
        # nykyinen suhteellinen etaisyys katselupisteesta, 0..1
        self.viewZoom = 0.5
        
        # radians
        self.viewAngleX = 0
        # -1.. 1
        self.viewAngleZ = 0
    
    def SetFocusShip(self, ship):
        self.focusShip = ship
    
    def SpinCameraZ(self, length):
        percentage = length / self.mouseSensitivity
        self.viewAngleZ += percentage*2; # taysi kierros on -1..1, eli 2
        if self.viewAngleZ > 1.0:
            self.viewAngleZ = 1.0
        elif self.viewAngleZ < -1.0:
            self.viewAngleZ = -1.0
            
    def SpinCameraX(self, length):
        percentage = length / self.mouseSensitivity
        self.viewAngleX += percentage * 2 * pi;
        while self.viewAngleX > 2*pi:
            self.viewAngleX -= 2*pi
        while self.viewAngleX < 0:
            self.viewAngleX += 2*pi

    
    def PositionCamera(self):
        if (self.focusShip != None):
            #min, max = self.focusShip.getTightBounds()
            med = self.focusShip.getPos()
        else:
            med = Point3(0,0,0)

        
        self.camera.setPos(med.getX() +      self.viewMaxDistance * self.viewZoom * sin(self.viewAngleX), 
                           med.getY() + -1 * self.viewMaxDistance * self.viewZoom * cos(self.viewAngleX), 
                           med.getZ() +      self.viewMaxDistance * self.viewZoom * self.viewAngleZ)

        self.camera.lookAt(med.getX(), med.getY(), med.getZ())
        
    
    def ZoomIn(self):
        self.viewZoom += 0.1
        if self.viewZoom > 1.0:
            self.viewZoom = 1.0
        self.PositionCamera()
        
    def ZoomOut(self):
        self.viewZoom -= 0.1
        if self.viewZoom < 0.1:
            self.viewZoom = 0.1
        self.PositionCamera()